package com.haiya.domain.service;

import com.haiya.domain.aggregate.cargo.Cargo;
import com.haiya.domain.aggregate.handleevent.HandlingEvent;
import com.haiya.infrastructure.rpc.salessystem.SalersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * 货物领域服务(Domain Service)
 * @author qiaoguoqiang
 */
@Service
public class CargoDomainService {
    @Autowired
    private SalersService salersService;

    public static final int MAX_CARGO_LIMIT = 10;

    /**
     * 货物编号前缀
     */
    public static final String PREFIX_ID = "CARGO-NO-";

    /**
     * 货物物流ID生成规则: 这里仅模拟，用随机生成的整型
     * @return
     */
    public static String nextCargoId() {
        return PREFIX_ID + (10000 + new Random().nextInt(9999));
    }

    public void updateCargoSender(Cargo cargo, String senderPhone, HandlingEvent latestEvent) {
        if (null != latestEvent
                && !latestEvent.canModifyCargo()) { throw new IllegalArgumentException(
                "Sender cannot be changed after RECIEVER Status."); }

        cargo.changeSender(senderPhone);
    }

    public boolean mayAccept(int size, int cargoSize, Cargo cargo) {
        return size <= MAX_CARGO_LIMIT && salersService.mayAccept(cargoSize, cargo);
    }
}
